package com.codermn.并发访问控制.信号量;

import java.util.concurrent.Semaphore;

/**
 * <p>
 *     可以使用信号量Semaphore来完成，通过设置信号量，来控制并发数
 * </p>
 * @author jxau_scf
 * @date 2021/8/13 - 11:13
 */
public class SemaphoreDemo {
    private void semConsumer(Semaphore semaphore){

        try {
            //同步阻塞，尝试获取信号
            semaphore.acquire(1);
            System.out.println("成功拿到信号，执行   " + Thread.currentThread());
            Thread.sleep(2000);
            System.out.println("执行完毕，释放信号   " + Thread.currentThread());
            semaphore.release(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    public void semaphore() throws InterruptedException {
//        可以使用信号量Semaphore来完成，通过设置信号量，来控制并发数
        Semaphore semaphore = new Semaphore(2);

        new Thread(()->semConsumer(semaphore)).start();
        new Thread(()->semConsumer(semaphore)).start();
        new Thread(()->semConsumer(semaphore)).start();
        new Thread(()->semConsumer(semaphore)).start();
        new Thread(()->semConsumer(semaphore)).start();

        Thread.sleep(2000);
    }
}
